<?php

namespace app\api\controller\v50;

use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserSameQuestion;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Env;
use think\Log;

class UserQuestionAnswer extends Auth
{
    /**
     * 发布问题
     */
    public function questionAdd()
    {
        $qid = input('qid/d', 0);
        $qtype = input('qtype/d', 0);   // 1=>别人的提问 2=>猜你想问
        $questionType = input('question_type/d', 0); // 0=>免费问题 , 1=>星盘问题,2=>骰子问题,3=>塔罗问题 （1、2、3属于悬赏问题）
        $question = input('question/s', '');
        $astroData = input('astro_data/s', '');
        $diceData = input('dice_data/s', '');
        $tarotData = input('tarot_data/s', '');
        $gid = input('gid/d', 0);
        $isAnonymity = input('is_anonymity/d', 0);  // 是否匿名
        $isHide = input('is_hide/d', 0);
        if (!$question)
        {
            return show(config('code.error'), '请输入咨询问题');
        }

        if (mb_strlen($question) > 120)
        {
            return show(config('code.error'), '咨询问题最多120字');
        }
        if (!in_array($questionType, [1, 2, 3,], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (!in_array($isAnonymity, [0, 1], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], [
            'question_type' => $questionType,
            'question' => $question,
            'astro_data' => $astroData,
            'dice_data' => $diceData,
            'tarot_data' => $tarotData,
            'gid' => $gid,
            'is_anonymity' => $isAnonymity,
            'is_hide' => $isHide,
        ]))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }

        $res = AliyunFilterWord::checkText($question, 'question_pic_check');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
//            return [
//                'status' => false,
//                'msg' => '问题中有敏感词'
//            ];
            return show(config('code.toast'), '问题中有敏感词');
        }

        $questionData = [
            'id' => Util::createQuestionAnswerId(),
            'uid' => $this->user['id'],
            'status' => 0,
            'question_type' => $questionType,
            'question' => $question,
            'question_des' => '',
            'question_imgs' => '',
            'gid' => $gid,
            'is_anonymity' => $isAnonymity,
            'is_read' => 1,
            'create_time' => $this->request->time(),
        ];
        // 记录 占星师下单时的版本号
        $questionExtend = ['version' => $this->headers['version']];
        //獲取當前商品所屬問題類型
        $questionTypeInfo = (new Zlcr2UserQuestion())->getQuestionType($gid);
        if (isset($questionTypeInfo['sec']) && $questionTypeInfo['sec'] !== $questionType)
        {
            return show(config('code.error'), '服务异常');
        }

        $isSynastry = 0; // 是否合盘
        switch ($questionType)
        {
            case 1: // 看盘
                $astroData = json_decode($astroData, true);
                if (!$astroData || !isset($astroData['rid1'], $astroData['astro_type']) || !$astroData['rid1'] || !in_array($astroData['astro_type'], [1, 2], false))
                {
                    return show(config('code.error'), '请求异常，请稍后再试～');
                }

                $recodeInfo1 = (new Recode())->getRecode(['id' => $astroData['rid1']]);
                if (!$recodeInfo1 || $recodeInfo1['uid'] != $this->user['id'])
                {
                    return show(config('code.error'), '请求异常！档案信息不存在～');
                }
                $questionExtend['recode1'] = [
                    'id' => (int)$astroData['rid1'],
                    'avatar' => $recodeInfo1['avatar'],
                    "name" => $recodeInfo1['name'],
                    "type" => (int)$recodeInfo1['type'],
                    "year" => (int)$recodeInfo1['year'],
                    "month" => (int)$recodeInfo1['month'],
                    "day" => (int)$recodeInfo1['day'],
                    "hour" => (int)$recodeInfo1['hour'],
                    "minute" => (int)$recodeInfo1['minute'],
                    "timezone" => (int)$recodeInfo1['timezone'],
                    "long_deg" => (int)$recodeInfo1['long_deg'],
                    "long_min" => (int)$recodeInfo1['long_min'],
                    "ew" => (int)$recodeInfo1['ew'],
                    "lat_deg" => (int)$recodeInfo1['lat_deg'],
                    "lat_min" => (int)$recodeInfo1['lat_min'],
                    "ns" => (int)$recodeInfo1['ns'],
                    "is_summer" => (int)$recodeInfo1['is_summer'],
                    "birth_country" => $recodeInfo1['birth_country'],
                    "birth_province" => $recodeInfo1['birth_province'],
                    "birth_city" => $recodeInfo1['birth_city'],
                    "live_country" => $recodeInfo1['live_country'],
                    "live_province" => $recodeInfo1['live_province'],
                    "live_city" => $recodeInfo1['live_city'],
                    "isself" => (int)$recodeInfo1['isself'],
                ];

                if ($astroData['astro_type'] == 2)
                {
                    $recodeInfo2 = (new Recode())->getRecode(['id' => $astroData['rid2']]);
                    if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'])
                    {
                        return show(config('code.error'), '请求异常！档案信息不存在～');
                    }
                    $questionExtend['recode2'] = [
                        'id' => (int)$astroData['rid2'],
                        'avatar' => $recodeInfo2['avatar'],
                        "name" => $recodeInfo2['name'],
                        "type" => (int)$recodeInfo2['type'],
                        "year" => (int)$recodeInfo2['year'],
                        "month" => (int)$recodeInfo2['month'],
                        "day" => (int)$recodeInfo2['day'],
                        "hour" => (int)$recodeInfo2['hour'],
                        "minute" => (int)$recodeInfo2['minute'],
                        "timezone" => (int)$recodeInfo2['timezone'],
                        "long_deg" => (int)$recodeInfo2['long_deg'],
                        "long_min" => (int)$recodeInfo2['long_min'],
                        "ew" => (int)$recodeInfo2['ew'],
                        "lat_deg" => (int)$recodeInfo2['lat_deg'],
                        "lat_min" => (int)$recodeInfo2['lat_min'],
                        "ns" => (int)$recodeInfo2['ns'],
                        "is_summer" => (int)$recodeInfo2['is_summer'],
                        "birth_country" => $recodeInfo2['birth_country'],
                        "birth_province" => $recodeInfo2['birth_province'],
                        "birth_city" => $recodeInfo2['birth_city'],
                        "live_country" => $recodeInfo2['live_country'],
                        "live_province" => $recodeInfo2['live_province'],
                        "live_city" => $recodeInfo2['live_city'],
                        "isself" => (int)$recodeInfo2['isself'],
                    ];
                    $isSynastry = 1;
                }
                break;
            case 2: // 骰子
                $diceData = $diceData ? json_decode($diceData, true) : [];
                if (!$diceData || !isset($diceData['planet'], $diceData['sign'], $diceData['house']))
                {
                    return show(config('code.error'), '咨询骰子数据异常！');
                }
                $questionExtend['dice_data'] = $diceData;
                break;
            case 3: // 塔罗
                $tarotData = $tarotData ? json_decode($tarotData, true) : [];
                if (!$tarotData || count($tarotData) !== 3)
                {
                    return show(config('code.error'), '咨询塔罗数据异常！');
                }
                foreach ($tarotData as $item)
                {
                    if (!isset($item['img'], $item['tips'], $item['name']))
                    {
                        return show(config('code.error'), '咨询塔罗数据异常！');
                    }
                }
                $questionExtend['tarot_data'] = $tarotData;
                break;
            default:
        }

        $questionData['is_synastry'] = $isSynastry; // 是否合盘
        $questionData['is_hide'] = $this->user['no_comment'] ? 1 : 0;
        $questionData['question_extend'] = json_encode($questionExtend, JSON_UNESCAPED_UNICODE);
        if ($isHide === 1)
        {
            $questionData['is_hide'] = 1;
        }
        try
        {
            $questionModel = new Zlcr2UserQuestion();
            $res = $questionModel->SaveData($this->user['id'], $questionData);
            if (!$res)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            if ($qid)
            {   // 同问 数增加
                if ($qtype === 1)
                {
                    $questionInfo = $questionModel->getInfoById($qid, ['read_num', 'comment_num', 'same_num', 'id', 'consult_time', 'status', 'is_hide']);
                    $questionModel->UpdateData($qid, ['same_num' => $questionInfo['same_num'] + 1]);
                    // 更新 推荐值
                    $questionModel->changeQuestionInfo($questionInfo, 3, 1);
                } else
                {
                    $guessQuestionModel = new \app\common\cachemodel\zlcr2\GuessQuestion();
                    $questionInfo = $guessQuestionModel->getInfoById($qid, ['same_num']);
                    $guessQuestionModel->UpdateData($qid, ['same_num' => $questionInfo['same_num'] + 1]);
                }

                (new Zlcr2UserSameQuestion())->SaveData([
                    'uid' => $this->user['id'],
                    'type' => $qtype === 1 ? 1 : 2,
                    'same_qid' => $qid,
                    'qid' => $questionData['id'],
                    'create_time' => $this->request->time(),
                ]);
            }

            return show(config('code.success'), '发布成功', ['qid' => $questionData['id']]);
        }
        catch (\Exception $e)
        {
            Log::write('问答 v50/UserQuestionAnswer => questionAdd()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}